<?php
declare (strict_types = 1);

namespace app\validate\common\system;

use think\Validate;
use app\model\communal\DepartmentModel;

class DepartmentValidate extends Validate
{
    protected $field = [
        'id' => 'ID',
        'pid' => '上级部门',
        'level' => '部门层级',
        'name' => '部门名称',

        'page' => '当前页数',
        'page_size' => '每页条数',
    ];

    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id' => ['require', 'number', 'gt:0'],
        'pid' => ['number', 'gt:0', 'different:id'],
        'level' => ['number', 'egt:1', 'elt:10'],
        'name' => ['require', 'max:25'],

        'page' => ['number', 'gt:0'],
        'page_size' => ['number', 'gt:0'],
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [];

    /**
     * 场景
     * @var array
     */
    protected $scene = [
        'index' => ['page', 'page_size'],
        'parents' => ['id'],
        'staffs' => ['ids', 'staff_ids'],
    ];

    /**
     * scene save
     *
     * @return $this
     */
    public function sceneSave()
    {
        return $this->only(DepartmentModel::$saveColumn)
            ->append('name', 'checkNameUnique:save');
    }

    /**
     * scene update
     *
     * @return $this
     */
    public function sceneUpdate()
    {
        return $this->only(DepartmentModel::$updateColumn)
            ->append('name', 'checkNameUnique:update');
    }

    /**
     * scene update item
     *
     * @return $this
     */
    public function sceneItem()
    {
        return $this->only(['id', 'name'])
            ->remove('name', 'require');
    }

    /**
     * 公司部门名称唯一验证
     *
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|mixed
     */
    public function checkNameUnique($value, $rule, $data)
    {
        $data['delete_at'] = 0;
        $data['company_id'] = request()->middleware('company')['company_id'];
        if ('save' === $rule) {
            $check = $this->unique($value, DepartmentModel::class . ',company_id^name^delete_at', $data, 'company_id^name^delete_at');
        } else {
            $check = $this->unique($value,DepartmentModel::class . ',company_id^name^delete_at,' . $data['id'], $data, 'company_id^name^delete_at');
        }

        if (true !== $check) {
            return lang(':attribute has exists');
        }

        return true;
    }
}
